﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using MAPIdotnet;

namespace OutlookHub.Models
{
    public class Message:IDisposable
    {
        private string body;
        private IMAPIMessage msg;
        private static Dictionary<byte[], Message> messages = new Dictionary<byte[], Message>();

        private Message(IMAPIMessage msg)
            : base()
        {
            this.msg = msg;
            Flags = msg.Flags;
            Sender = msg.Sender.Name.Trim();
            Subject = msg.Subject.Trim();
            DeliveryDate = msg.LocalDeliveryTime; // DateTime.FromFileTimeUtc((long)msg.SystemDeliveryTime);
            Recipients = msg.Recipients;
        }

        public void Dispose()
        {
            RemoveFolder(this);
            GC.SuppressFinalize(this);
        }

        ~Message()
        {
            Dispose();
        }

        private static void RemoveFolder(Message message)
        {
            messages.Remove(message.msg.MessageID.AsByteArray);
        }

        public static Message CreateMessage(IMAPIMessage imsg)
        {
            Message msg;
            var msgId = imsg.MessageID;
            byte[] key = msgId.AsByteArray;
            if (messages.TryGetValue(key, out msg)) return msg;

            msg = new Message(imsg);
            messages.Add(key, msg);
            return msg;
        }


        public FollowUpStatus Flagged
        {
            get { return msg.StatusFlags; }
            set { msg.StatusFlags = value; }
        }

        public IMAPIAttachment[] Attachments
        {
            get { return msg.Attachments; }
        }

        public Priority Priority { get { return msg.Priority; } set { msg.Priority = value; } }

        public int Size { get { return msg.Size; } }
        public bool IsChecked { get; set; }
        public IMAPIContact[] Recipients { get; private set; }
        public bool ReadFlag { get { return (Flags & EMessageFlags.MSGFLAG_READ) != 0; } }
        public DateTime DeliveryDate { get; set; }
        public string Subject { get; private set; }
        public string Sender { get; private set; }
        public EMessageFlags Flags { get; private set; }

        public string Body
        {
            get
            {
                if (body == null)
                {
                    body = msg.Body;
                    if (body == null) body = string.Empty;
                }
                return body;
            }
        }

    }
}
